package com.cbtx.module_sp.ui.fragment

import android.content.Context
import android.media.MediaPlayer
import android.media.MediaPlayer.*
import android.os.Build
import android.os.Bundle
import android.view.SurfaceHolder
import android.view.View
import android.view.WindowManager
import androidx.core.content.ContextCompat.getSystemService
import com.bumptech.glide.Glide
import com.cbtx.module.base.ui.BaseVMFragment
import com.cbtx.module_sp.R
import com.cbtx.module_sp.ui.vm.AdvFragmentVM
import com.txcb.lib.base.utils.UIUtil
import kotlinx.android.synthetic.main.sp_fragment_adv_video.*
import org.greenrobot.eventbus.EventBus


/**
 * @author : Lambert
 * date   : 2020/10/29 2:26 PM
 */
class AdvVideoFragment(val bannerType:Int, val mVideoUrl: String) : BaseVMFragment<AdvFragmentVM>(),
    SurfaceHolder.Callback, OnBufferingUpdateListener, OnPreparedListener, OnCompletionListener {


    private var mMediaPlayer: MediaPlayer? = null
    private var mPosition = 0
    private val hasActiveHolder = false



    override fun getPresenterClazz(): Class<AdvFragmentVM> {
        return AdvFragmentVM::class.java
    }

    override fun setLayout(): Any {
        return R.layout.sp_fragment_adv_video
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {

        if(bannerType ==2){
            initPlayVideo()
        }

        Glide.with(activity!!).load(mVideoUrl).into(mIvAdvCover)

    }


    override fun lazyData() {
        super.lazyData()
        if(bannerType ==2) {
            play()
        }

    }
    /**
     * 播放视频
     */
    fun initPlayVideo() {
        if (mMediaPlayer == null) {
            //实例化MediaPlayer对象
            mMediaPlayer = MediaPlayer()

            val mHardwareDecoder = false
            // 不维持自身缓冲区，直接显示
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && mHardwareDecoder) {
                mSurfaceView!!.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
            }
            mSurfaceView.getHolder().setFixedSize(UIUtil.getWidowsWidth(activity), UIUtil.getWidowsHeight(activity));
            mSurfaceView!!.holder.setKeepScreenOn(true) //保持屏幕常亮
            mSurfaceView!!.holder.addCallback(this)
        }
    }


    override fun onDestroy() {
        //释放内存，MediaPlayer底层是运行C++的函数方法，不使用后必需释放内存
        if (mMediaPlayer != null) {
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.pause()
                mPosition = mMediaPlayer!!.currentPosition
            }
            mMediaPlayer!!.release()
            mMediaPlayer = null
        }
        super.onDestroy()
    }


    /**
     * begin
     * 向player中设置dispay，也就是SurfaceHolder。但此时有可能SurfaceView还没有创建成功，所以需要监听SurfaceView的创建事件
     */
    override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
    }

    override fun surfaceDestroyed(p0: SurfaceHolder) {
        mMediaPlayer?.stop()
    }

    override fun surfaceCreated(p0: SurfaceHolder) {

        if (userVisibleHint) {
            play()
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()

        stopPlay()
    }


    /**
     * end
     * 向player中设置dispay，也就是SurfaceHolder。但此时有可能SurfaceView还没有创建成功，所以需要监听SurfaceView的创建事件
     */


    private fun play() {
        try {
            if (mMediaPlayer == null){
                mMediaPlayer = MediaPlayer()
            }
            //添加播放视频的路径与配置MediaPlayer
            mMediaPlayer?.reset()
            //给mMediaPlayer添加预览的SurfaceHolder，将播放器和SurfaceView关联起来
            mMediaPlayer?.setDisplay(mSurfaceView.holder)
            mMediaPlayer?.setDataSource(mVideoUrl)
            // 缓冲
            mMediaPlayer?.prepare()
            mMediaPlayer?.setOnBufferingUpdateListener(this)
            mMediaPlayer?.setOnPreparedListener(this)
            mMediaPlayer?.setOnCompletionListener(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 缓冲变化时回调
     */
    override fun onBufferingUpdate(p0: MediaPlayer?, p1: Int) {

    }

    /**
     * 准备完成回调
     * 只有当播放器准备好了之后才能够播放，所以播放的出发只能在触发了prepare之后
     */
    override fun onPrepared(p0: MediaPlayer?) {
        mMediaPlayer?.start()

        mIvAdvCover.visibility = View.GONE
//                mMediaPlayer.seekTo(position)

    }

    /**
     * 播放结束时回调
     */
    override fun onCompletion(p0: MediaPlayer?) {
//        mMediaPlayer.start()


        stopPlay()
        EventBus.getDefault().post("nextAdv")
    }


    fun stopPlay(){
        if (mMediaPlayer != null){
            if (mMediaPlayer?.isPlaying!!){
                mMediaPlayer?.stop()
                mMediaPlayer?.release()

                mMediaPlayer = null
            }
        }
    }
}